package com.adnaan.backend.controller.admin;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.SupplierApplication;
import com.adnaan.backend.entity.SysUser;
import com.adnaan.backend.entity.vo.AuditVo;
import com.adnaan.backend.service.SupplierApplicationService;
import com.adnaan.backend.service.SysUserService;
import com.adnaan.backend.utils.PasswordUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@RestControllerMapping("/supplier/application")
@Tag(name = "供货商申请管理", description = "供货商申请管理")
@ApiSupport(author = "adnaan", order = 2)
@Slf4j
public class SupplierApplicationController {

    @Resource
    private SupplierApplicationService supplierApplicationService;

    @Resource
    private SysUserService sysUserService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @GetMapping("/info/{id}")
    @ApiOperationSupport(order = 1)
    @Operation(summary = "通过ID查询单条数据")
    public Result<SupplierApplication> getById(@PathVariable Long id) {
        return Result.success(supplierApplicationService.getById(id));
    }

    /**
     * 分页查询
     *
     * @param pageParams 分页对象
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页查询")
    public Result<Page<SupplierApplication>> pageQuery(@RequestBody PageParams<SupplierApplication> pageParams) {
        SupplierApplication params = pageParams.getParams();
        LambdaQueryWrapper<SupplierApplication> lqw = new LambdaQueryWrapper<>();
        lqw.eq(params.getUserId() != null, SupplierApplication::getUserId, params.getUserId())
                .eq(params.getStatus() != null, SupplierApplication::getStatus, params.getStatus())
                .like(StrUtil.isNotBlank(params.getCompanyName()), SupplierApplication::getCompanyName, params.getCompanyName())
                .like(StrUtil.isNotBlank(params.getLegalPerson()), SupplierApplication::getLegalPerson, params.getLegalPerson())
                .like(StrUtil.isNotBlank(params.getContactPhone()), SupplierApplication::getContactPhone, params.getContactPhone())
                .orderByDesc(SupplierApplication::getCreateTime);
        return Result.success(supplierApplicationService.page(pageParams.getPage(), lqw));
    }

    /**
     * 新增申请
     *
     * @param application 实例对象
     * @return 实例对象
     */
    @PostMapping("/insert")
    @SaIgnore
    @ApiOperationSupport(order = 3)
    @Operation(summary = "新增申请")
    public Result<Boolean> add(@RequestBody SupplierApplication application) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, application.getContactPhone())
                .or()
                .eq(SysUser::getPhone, application.getContactPhone());

        SysUser user = sysUserService.getOne(queryWrapper);
        if (user == null) {
            user = new SysUser();
            user.setUsername(application.getContactPhone());
            String salt = RandomUtil.randomString(16);
            user.setSalt(salt);
            String encrypt = PasswordUtils.encrypt(application.getPassword(), salt);
            user.setPassword(encrypt);
            user.setStatus(0);
            user.setPhone(application.getContactPhone());
            user.setNickname(application.getCompanyName());
            user.setEmail(application.getEmail());

            try {
                sysUserService.save(user);
                //只有一个角色，转为List
                List<String> roleIds = List.of("6");
                sysUserService.insertRoles(user.getId(), roleIds);
                if (user.getId() == null) {
                    return Result.error("用户创建失败，请检查字段约束");
                }
                // 设置申请用户ID
                application.setUserId(user.getId());
                // 设置初始状态为待审核
                application.setStatus(0);
                supplierApplicationService.save(application);
                return Result.success();
            } catch (Exception e) {
                log.info("保存用户失败:{ }", e);
                return Result.error("创建失败，请联系管理员");
            }
        }
        return Result.error("该手机号已存在");
    }

    /**
     * 审核申请
     *
     * @param auditVo shiti
     * @return 是否成功
     */
    @PostMapping("/audit")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "审核申请")
    public Result<Boolean> audit(@RequestBody AuditVo auditVo) {
        return Result.success(supplierApplicationService.audit(auditVo.getId(), auditVo.getStatus(), auditVo.getRejectReason()));
    }
}